package xtreamclient.util

import kotlinx.coroutines.*
import kotlinx.coroutines.time.delay
import java.time.Duration

class BufferedAsync<T>(coroutineScope: CoroutineScope, doEvery: Duration,doUpdate: suspend () -> T) {
    var buffer:T? = null
    val handler = CoroutineExceptionHandler { _, exception ->
        println("Caught $exception")
    }

    init {
        coroutineScope.launch(handler) {
            while (true) {
                buffer = doUpdate()
                delay(doEvery)
            }
        }
    }

    fun getOrNull():T? {
        return buffer
    }
}

